
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <uv.h>
#include <functional>
#include <thread>
#include <iostream>
#include <Windows.h>

uv_async_t async;
uv_async_t async2;
uv_async_t stopsig;  

uv_loop_t* loop;
 
void close_cb(uv_handle_t* handle);
void async_cb(uv_async_t* handle, int status);
 
void close_cb(uv_handle_t* handle)
{
	printf("close the async handle!\n");
}
 
void async_cb(uv_async_t* handle)
{
    int id = GetCurrentThreadId();
	printf("async_cb called!\n");
	printf("thread id:%lu.\n", id);

}
 
void async_cb2(uv_async_t* handle)
{
    int id = GetCurrentThreadId();
	printf("async_cb2 called!\n");
	printf("thread id:%lu.\n", id);

}

void idle_cb(uv_async_t *handle) {
	printf("Idle callback\n");
	uv_stop(uv_default_loop());  // 一定要在回调函数内去调用,主函数内调用不生效。
}


int main()
{
	loop = uv_default_loop();
 
	int id = GetCurrentThreadId();
	printf("thread id:%lu.\n", id);

	uv_async_init(loop, &async, async_cb);
    uv_async_init(loop, &async2, async_cb2);
    uv_async_init(loop, &stopsig, idle_cb);

	uv_async_send(&async);
    std::thread t1([]()->int{ 
        Sleep(2000);
        std::cout<<"start\r\n";
        int id = GetCurrentThreadId();
	    printf("thread id:%lu.\n", id);
	    uv_async_send(&async);
        Sleep(1000);
	    uv_async_send(&async2);
        Sleep(5000);
        std::cout<<"stop\r\n";
	    uv_async_send(&stopsig);
        std::cout<<"stop\r\n";
        return 1;
    });
    t1.detach();
	uv_run(loop, UV_RUN_DEFAULT);

	return 0;
}



